package main

import (
	"fmt"
	"image"
	"image/color"
	"image/draw"

	p9 "code.google.com/p/jnj.plan9/draw"
)

var (
	disp    *p9.Display
	mc      *p9.Mousectl
	kc      *p9.Keyboardctl
	waveimg *image.RGBA
	black   color.RGBA = color.RGBA{0, 0, 0, 0xff}
)

func visInit() {
	waveimg = image.NewRGBA(image.Rect(0, 0, bufsize, bufsize))

	var err error
	winsize := fmt.Sprintf("%dx%d", bufsize, bufsize+22)
	disp, err = p9.Init(nil, "synth", winsize)
	die(err)

	mc = disp.InitMouse()
	kc = disp.InitKeyboard()

	go handleEvents()
}

func handleEvents() {
	for {
		select {
		case me := <-mc.C:
			if me.Buttons == 1 {
				if limit1 < bufsize {
					limit1 <<= 1
				} else {
					limit1 = 1
				}
			}
		case ke := <-kc.C:
			// esc
			if ke == 27 {
				disp.Close()
				cleanup()
			}
		}
	}
}

func vis(buf []int32) {
	draw.Draw(waveimg, waveimg.Bounds(), image.White, image.ZP, draw.Src)
	for col, s := range buf {
		waveimg.Set(col, bufsize/2+int(s>>25), black)
	}
	_, err := disp.ScreenImage.Load(waveimg.Bounds(), waveimg.Pix)
	die(err)
	disp.Flush()
}
